using Microsoft.EntityFrameworkCore;
using Npgsql;
using UniversalAdminSystem.Domian.Core.Interfaces;
using UniversalAdminSystem.Infrastructure.Persistence.DbContexts;

namespace UniversalAdminSystem.Infrastructure.Persistence.Repositories;

/// <summary>
/// 基础仓储，基本CRUD可重写
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseRepository<T> : IRepository<T> where T : class
{
    protected readonly UniversalAdminSystemDbContext _DbContext;
    protected readonly DbSet<T> _TDs;


    public BaseRepository(UniversalAdminSystemDbContext dbContext)
    {
        _DbContext = dbContext;
        _TDs = dbContext.Set<T>();
    }

    public virtual async Task<T> AddAsync(T entity)
    {
        try
        {
            var list = (await _TDs.AddAsync(entity)).Entity;
        
            return list;
        }
        catch (DbUpdateException ex)
        {
            // 处理数据库更新异常
            throw new Exception("数据库更新异常", ex);
        }
        catch (ArgumentNullException ex)
        {
            // 处理空参数异常
            throw new ArgumentNullException("实体不能为空", ex);
        }
    }

    public virtual async Task<IEnumerable<T>> GetAllAsync()
    {
        var list = await _TDs.AsNoTracking().ToListAsync();
        return list;
    }

    public virtual async Task<T?> GetByGuidAsync(Guid guid)
    {
        var list = await _TDs.FindAsync(guid);
        return list;
    }

    public virtual async Task RemoveAsync(Guid guid)
    {
        var user = await GetByGuidAsync(guid);

        if (user == null) return;

        _TDs.Remove(user);
        
    }

    public async Task Update(T entity)
    {
        await Task.Run(() => _TDs.Update(entity));
    }
}